﻿//
// USBCError.cs
//
// Authors:
//    Claus Jørgensen <10229@iha.dk>
//    Jens Bloch Christensen <09584@iha.dk>
//    Jonas Daugaard Møller <08814@iha.dk>
//
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace RSD.Robot
{
    /// <summary>
    /// Managed error data structure.
    /// </summary>
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct USBCError
    {
        /// <summary>
        /// Error number.
        /// </summary>
        public int Number;

        /// <summary>
        /// Active axis.
        /// </summary>
        public byte Axis;

        /// <summary>
        /// Reserved.
        /// </summary>
        public uint Reserved1;

        /// <summary>
        /// Reserved.
        /// </summary>
        public uint Reserved2;

        /// <summary>
        /// Contains information about the error message, 
        /// and possible also information about time of the error
        /// and the error number as defined in ERROR.h
        /// </summary>
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 81)]
        public byte[] Optional;

        /// <summary>
        /// Gets a message that describes the current error.
        /// </summary>
        /// <returns>The error message.</returns>
        public string GetMessage()
        {
            if (Optional != null)
            {
                var message = UTF8Encoding.UTF8.GetString(
                    Optional.Skip(16).ToArray());

                int nullTermination = message.IndexOf('\0');
                if (nullTermination >= 0)
                {
                    return message.Substring(0, nullTermination);
                }

                return message;
            }

            return string.Empty;
        }
    }
}
